<template>
  <div>
    <SearchForm
      @search="onSearch"
      @reset="onReset"
      :search-list="searchList"
      :search-params="searchParams"
    >
      <template #button>
        <el-button type="primary" size="mini" @click="onAdd">新增商品</el-button>
      </template>
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-box">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              max-height="500px"
              :data="tableData"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
              @selection-change="onSelect"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column align="center" label="ID" prop="id" width="80" />
            <el-table-column align="center" label="商品图片" width="100">
              <template slot-scope="scope">
                <el-image
                    v-if="scope.row.items[0].thumbnail"
                    style="width: 60px; height: 60px"
                    :src="scope.row.items[0].thumbnail"
                    :preview-src-list="[scope.row.items[0].thumbnail]"
                ></el-image>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="商品名称" prop="items[0].name" />
            <el-table-column align="center" label="分类" width="120">
              <template slot-scope="scope">
                {{ scope.row.category ? scope.row.category.name : '-' }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="价格" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.items[0].price }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="成本价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.items[0].cost_price }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="库存" prop="items[0].stock" width="80" />
            <el-table-column align="center" label="销量" prop="sales" width="80" />
            <el-table-column align="center" label="状态" width="80">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.items[0].status === 1">上架</el-tag>
                <el-tag type="danger" v-else>下架</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button
                    type="text"
                    @click="changeStatus(scope.row)"
                    :style="{ color: scope.row.items[0].status === 1 ? '#F56C6C' : '#67C23A' }"
                >
                  {{ scope.row.items[0].status === 1 ? '下架' : '上架' }}
                </el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
      </el-card>

      <div class="page-box">
        <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
        />
      </div>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      top="5vh"
      :close-on-click-modal="false"
    >
      <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        :loading="formLoading"
        @save="onSaveProduct"
        @close="dialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import { http, uploadFile } from "@/api";

export default {
  name: "OfficeProductIndex",
  mixins: [crud],
  data() {
    return {
      request: http.officeProduct,
      searchList: [
        {
          label: '商品名称',
          prop: 'name',
          name: 'input',
          clearable: true
        },
        {
          label: '分类',
          prop: 'category_id',
          name: 'select',
          clearable: true,
          options: []
        },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          clearable: true,
          options: [
            { label: '上架', value: 1 },
            { label: '下架', value: 0 }
          ]
        }
      ],
      searchParams: {
        name: '',
        category_id: '',
        status: ''
      },
      defaultParams: {
        type: 1,
      },
      dialogTitle: '添加商品',
      dialogVisible: false,
      formLoading: false,
      ruleForm: {
        type:1,
        name: '',
        category_id: '',
        price: 0,
        cost_price: 0,
        points_price: 0,
        stock: 0,
        status: 1,
        thumbnail: '',
        images: '',
        description: '',
        specifications: '',
        is_points_available: 0,
        is_mixed_payment: 0
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        category_id: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }]
      },
      formList: [
        {
          label: '商品名称',
          prop: 'name',
          name: 'input',
          placeholder: '请输入商品名称',
          colSpan: 8
        },
        {
          label: '商品分类',
          prop: 'category_id',
          name: 'select',
          placeholder: '请选择商品分类',
          options: [],
          colSpan: 8
        },
        {
          label: '销售价格',
          prop: 'price',
          name: 'number',
          min: 0,
          precision: 2,
          append: '元',
          colSpan: 8
        },
        {
          label: '成本价格',
          prop: 'cost_price',
          name: 'number',
          min: 0,
          precision: 2,
          append: '元',
          colSpan: 8
        },
        {
          label: '商品库存',
          prop: 'stock',
          name: 'number',
          min: 0,
          colSpan: 8
        },
        {
          label: '商品规格',
          prop: 'specifications',
          name: 'input',
          rows: 4,
          placeholder: '请输入商品规格',
          colSpan: 8
        },
        {
          label: '商品缩略图',
          prop: 'thumbnail',
          name: 'image',
          colSpan: 8
        },
        {
          label: '商品图片集',
          prop: 'images',
          name: 'image',
          multiple: true,
          colSpan: 8
        },
        {
          label: '商品状态',
          prop: 'status',
          name: 'switch',
          activeValue: 1,
          inactiveValue: 0,
          activeText: '上架',
          inactiveText: '下架',
          colSpan: 8
        },
        {
          label: '商品详情',
          prop: 'description',
          name: 'rich',
          colSpan: 24
        },
      ]
    };
  },
  mounted() {
    this.loadCategoryOptions();
  },
  methods: {
    loadCategoryOptions() {
      http.officeCategory.list({
        type: 1
      }).then(res => {
        const options = [];
        res.data.forEach(item => {
          options.push({
            label: item.name,
            value: item.id
          });
        });
        this.searchList[1].options = options;
        this.formList[1].options = options;
      });
    },
    onAdd() {
      this.dialogTitle = '添加商品';
      this.dialogVisible = true;
      this.ruleForm = {
        name: '',
        type: 1,
        category_id: '',
        price: 0,
        points_price: 0,
        stock: 0,
        status: 1,
        thumbnail: '',
        images: '',
        description: '',
        specifications: '',
        is_points_available: 0,
        is_mixed_payment: 0
      };
    },
    onEdit(row) {
      this.dialogTitle = '编辑商品';
      this.dialogVisible = true;
      console.log('编辑')
      http.officeProduct.read(row.id).then(res => {
        this.ruleForm = { ...res.data };
      })
    },
    async onSaveProduct() {
      this.formLoading = true;
      try {
        if (this.ruleForm.id) {
          await http.officeProduct.update(this.ruleForm.id, this.ruleForm);
        } else {
          await http.officeProduct.create(null, this.ruleForm);
        }
        this.$message.success('保存成功');
        this.dialogVisible = false;
        this.onSearch();
      } catch (error) {
        console.error(error);
        this.$message.error('保存失败');
      } finally {
        this.formLoading = false;
      }
    },
    async changeStatus(row) {
      try {
        const newStatus = row.status === 1 ? 0 : 1;
        await http.officeProduct.update(row.id, { status: newStatus });
        this.$message.success(newStatus === 1 ? '商品已上架' : '商品已下架');
        this.onSearch();
      } catch (error) {
        console.error(error);
        this.$message.error('操作失败');
      }
    }
  }
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}
.page-box {
  margin-top: 20px;
  text-align: right;
}
</style>
